package com.hy.convenient.tool;

import com.alibaba.fastjson.JSON;
import com.hy.convenient.common.CommonData;
import com.hy.convenient.pojo.login.UsersPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisUitl {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public void set(final String key, Object value) {
        redisTemplate.opsForValue().set(CommonData.REDIS_PREFIX + key, value.toString());
    }

    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @param expireTime 缓存时长
     * @param timeUnit 时间类型
     * @return
     */
    public void set(final String key, Object value, long expireTime, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(CommonData.REDIS_PREFIX + key, value.toString(), expireTime,timeUnit);
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(CommonData.REDIS_PREFIX + key)) {
            redisTemplate.delete(CommonData.REDIS_PREFIX + key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(CommonData.REDIS_PREFIX + key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        return redisTemplate.opsForValue().get(CommonData.REDIS_PREFIX + key);
    }

    /**
     * 更新缓存时间
     * @param key
     */
    public  void expire(final String key){
        redisTemplate.expire(CommonData.REDIS_PREFIX + key, CommonData.EXPIRETIME_1_HOUR, TimeUnit.SECONDS);
    }

    /**
     * 获取redis中的缓存数据
     * @return
     */
    public UsersPojo getObject(final String key){
       return JSON.parseObject(get(key), UsersPojo.class);
    }
}
